package lj.courseinterect.dao;

import lj.courseinterect.dao.i.LocateInfoDao;
import lj.courseinterect.dao.i.MajorInfoDao;
import lj.courseinterect.entity.LocateInfo;
import lj.courseinterect.entity.MajorInfo;
import lj.courseinterect.entity.NoticeInfo;
import lj.courseinterect.entity.StudentCourse;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;
import java.util.List;

public class JpaLocateInfoDao extends JpaDao<LocateInfo, Long> implements LocateInfoDao {

    public JpaLocateInfoDao() {
        super(LocateInfo.class);
    }

    @Override
    @Transactional(readOnly = true)
    public LocateInfo findByStuIdAndCouId(Long stuId, Long couId){
        final CriteriaBuilder builder = this.getEntityManager().getCriteriaBuilder();
        final CriteriaQuery<LocateInfo> criteriaQuery = builder.createQuery(this.entityClass);

        Root<LocateInfo> root = criteriaQuery.from(this.entityClass);
        Path<String> stuPath = root.get("stuId");
        Path<String> couPath = root.get("couId");

        criteriaQuery.where(builder.and(builder.equal(stuPath, stuId), builder.equal(couPath, couId)));

        TypedQuery<LocateInfo> typedQuery = this.getEntityManager().createQuery(criteriaQuery);
        try{
            return typedQuery.getSingleResult();
        } catch (Exception ex){
            return null;
        }
    }

    @Override
    public List<LocateInfo> queryByCouId(Long couId) {
        final CriteriaBuilder builder = this.getEntityManager().getCriteriaBuilder();
        final CriteriaQuery<LocateInfo> criteriaQuery = builder.createQuery(this.entityClass);

        Root<LocateInfo> root = criteriaQuery.from(this.entityClass);
        Path<String> couPath = root.get("couId");

        criteriaQuery.where(builder.equal(couPath, couId));

        TypedQuery<LocateInfo> typedQuery = this.getEntityManager().createQuery(criteriaQuery);
        List<LocateInfo> locateInfos = typedQuery.getResultList();

        if(locateInfos.isEmpty()){
            return null;
        }

        return locateInfos;
    }

    @Override
    @Transactional
    public int deleteByCouId(Long couId) {
        String queryQuestion = "delete from LocateInfo l where l.couId = :couId";
        Query query = this.getEntityManager().createQuery(queryQuestion);

        query.setParameter("couId", couId);
        int num = query.executeUpdate();

        return num;
    }
}
